import { WXlOGIN, INFO_LOGIN } from "../constants/api/loginapi";
import { USER_ACCESS } from "../constants/sitevars"
import { cryptoStore } from "./cryptoFactory";


function formatUserInfo() {
    const storegedUser = cryptoStore.getStorageSync(USER_ACCESS)
    if (typeof storegedUser === 'object') {
        // 兼容旧数据加密
        cryptoStore.setStorageSync(USER_ACCESS, storegedUser)
    }
    const res = cryptoStore.getStorageSync(USER_ACCESS) || {};
    return res;
}

function goLogin(vm) {
    return new Promise((resolve, reject) => {
        wx.login({
            success: async (res) => {
                const { code } = res
                // 发送 res.code 到后台换取 openId, sessionKey, unionId
                const data = await vm.$request({
                    url: WXlOGIN,
                    needCode: false,
                    method: 'post',
                    data: { code },
                })
                cryptoStore.setStorageSync(USER_ACCESS, data);
                vm.globalData.hasLogined = true;
                resolve()
            },
            fail: reject
        })
    })
}

/**
 * @param {function} cb
 */
function getUserProfile(cb) {
    wx.getUserProfile({
        desc: '用于完善会员资料',
        success: async (infoObj) => {
            const { rawData, signature, encryptedData, iv } = infoObj
            let { user_info, ...extra } = cryptoStore.getStorageSync(USER_ACCESS)
            const { openid } = user_info || {}
            user_info = {
                ...user_info,
                ...(infoObj.userInfo || {}),
                openid
            }
            const data = await this.$request({
                url: INFO_LOGIN,
                method: 'post',
                data: { openid, rawData, signature, encryptedData, iv },
            })
            cryptoStore.setStorageSync(USER_ACCESS, {
                ...extra,
                ...data,
                user_info
            })
            cb && cb()
        },
        fail: console.warn
    })
}

/**
 * @description 初始化请求，获取用户信息等请求按顺序进行
 * @param {*} options
 */
function setRequestQueue(vm, options) {
    new Promise((resolve, reject) => {
        const { token } = formatUserInfo()
        if (!token) {
            goLogin(vm).then(resolve)
        } else {
            wx.checkSession({
                success: (res) => {
                    // session_key 未过期，并且在本生命周期一直有效
                    vm.globalData.hasLogined = true;
                    resolve()
                },
                fail: () => goLogin(vm).then(resolve),
                complete: () => { }
            })
        }
    })
}

export {
    formatUserInfo,
    setRequestQueue,
    getUserProfile,

}